package com.leoman.controller;

import com.leoman.common.DataTableFactory;
import com.leoman.controller.common.CommonController;
import com.leoman.core.Constant;
import com.leoman.entity.*;
import com.leoman.service.*;
import com.leoman.utils.DateUtils;
import com.leoman.utils.QiNiuUtils;
import com.leoman.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 公共方法控制层
 * Created by 涂奕恒 on 2016/10/18.
 */
@Controller
@RequestMapping(value = "common")
public class CommonsController {

    @Autowired
    private ProvinceService provinceService;

    @Autowired
    private CityService cityService;

    @Autowired
    private RegionService regionService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private ImageService imageService;

    @Autowired
    private LetterAnnexService letterAnnexService;

    @Autowired
    private TagService tagService;

    /**
     * 省份列表
     */
    @RequestMapping("/provinceList")
    @ResponseBody
    public List<Province> provinceList() {
        return provinceService.findAll();
    }

    /**
     * 城市列表
     */
    @RequestMapping("/cityList")
    @ResponseBody
    public List<City> cityList(Integer provinceId) {
        return cityService.findListByProvinceId(provinceId);
    }

    /**
     * 区域列表
     */
    @RequestMapping("/areaList")
    @ResponseBody
    public List<Region> areaList(Integer cityId) {
        return regionService.findListByCityId(cityId);
    }

    /**
     * 标签列表
     */
    @RequestMapping("/tagList")
    @ResponseBody
    public List<Tag> tagList() {
        return tagService.findAll();
    }

    /**
     * 信纸附属信息列表
     */
    @RequestMapping("/findListByType")
    @ResponseBody
    public List<LetterAnnex> findListByType(Integer type) {
        return letterAnnexService.findListByType(type);
    }

    /**
     * 评论列表（分页）
     */
    @RequestMapping("/commentList")
    public void list(HttpServletResponse response,
                     String content,
                     String userName,
                     String startTime,
                     String endTime,
                     Integer sourceId,
                     Integer type,
                     Integer draw,
                     Integer start,
                     Integer length) {
        if (null == start || start == 0) {
            start = 1;
        }
        int pageNum = CommonController.getPageNum(start, length);
        Page<Comment> page = commentService.pageByParams(content, userName, startTime, endTime, sourceId, type, pageNum, length);

        Map<String, Object> result = DataTableFactory.fitting(draw, page);
        WebUtil.printJson(response, result);
    }

    @RequestMapping("/comment/info")
    public String commentInfo(Integer commentId, Integer sourceId, Integer type, ModelMap model) {
        model.addAttribute("sourceId", sourceId);
        model.addAttribute("type", type);

        if (null != commentId) {
            Comment comment = commentService.getById(commentId);
            comment.setImageList(imageService.findListBySourceIdAndType(commentId, Constant.SOURCE_TYPE_COMMENT));
            model.addAttribute("comment", comment);
            model.addAttribute("createTime", DateUtils.longToStringWithFormat(comment.getCreateTime(), "yyyy-MM-dd hh:mm:ss"));

            if (type == 2) {
                return "backend/微音评论详情";
            }

            return "backend/评论详情";
        } else {
            if (type == 2) {
                return "backend/添加微音评论";
            }
            return "backend/添加评论";
        }
    }

    /**
     * 删除评论
     */
    @RequestMapping("/comment/delete")
    @ResponseBody
    public Integer deleteComment(Integer commentId) {
        return commentService.deleteComment(commentId);
    }

    /**
     * 批量删除评论
     */
    @RequestMapping("/comment/batchDelete")
    @ResponseBody
    public Integer batchDeleteComment(String ids) {
        try {
            return commentService.batchDelete(ids);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 添加评论
     */
    @RequestMapping("/comment/save")
    @ResponseBody
    public Integer saveComment(Integer sourceId, Integer type, String content, String tempAddImageIds, String tempDelImageIds) {
        return commentService.saveComment(sourceId, type, content, tempAddImageIds, tempDelImageIds);
    }

    /**
     * 添加微音评论
     */
    @RequestMapping("/comment/savePlus")
    @ResponseBody
    public Integer saveCommentPlus(Integer sourceId, Integer type, String content, MultipartRequest multipartRequest) {
        return commentService.saveComment(sourceId, type, content, multipartRequest);
    }

    /**
     * 上传缓存图片
     */
    @RequestMapping("/addTempImage")
    @ResponseBody
    public Image addTempImage(MultipartRequest multipartRequest) {
        Image image = new Image();

        try {
            MultipartFile multipartFile = multipartRequest.getFile("tempImage");

            // 验证图片格式
            String originalFileName = multipartFile.getOriginalFilename().toLowerCase();
            String fileType = originalFileName.substring(originalFileName.indexOf("."));

            List<String> list = new ArrayList<>();
            list.add(".jpg");
            list.add(".gif");
            list.add(".jpeg");
            list.add(".png");
            list.add(".bmp");

            if (!list.contains(fileType)) {
                return image;
            }

            // image.setUrl(QiNiuUtils.upload(multipartFile));
            image.setUrl("http://img.xiami.net/images/album/img2/111202/6763647601472612686_2.jpg");

            imageService.create(image);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return image;
    }

    /**
     * 上传缓存图片
     */
    @RequestMapping("/addTempImageEditor")
    public void addTempImageEditor(HttpServletRequest request, HttpServletResponse response, MultipartRequest multipartRequest) {
        try {
            response.setContentType("textml;charset=UTF-8");
            request.setCharacterEncoding("UTF-8");
            MultipartFile multipartFile = multipartRequest.getFile("customFileName");
            // 文件类型限制
            String[] allowedType = {"image/bmp", "image/gif", "image/jpeg", "image/png"};
            boolean allowed = Arrays.asList(allowedType).contains(multipartFile.getContentType());
            if (!allowed) {
                response.getWriter().write("error|不支持的类型");
                return;
            }
            // 图片大小限制
            if (multipartFile.getSize() > 5 * 1024 * 1024) {
                response.getWriter().write("error|图片大小不能超过5M");
                return;
            }

            // 返回图片的URL地址
            response.getWriter().write(QiNiuUtils.upload(multipartFile));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
